<template>
    <div class="padding20">
        <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图-->
        <el-card>
            <!--提示组件-->
            <el-alert
                title="添加商品信息"
                type="info"
                center
                show-icon
                :closable="false"
            >
            </el-alert>

            <!--步骤条-->
            <el-steps :active="activeIndex - 0" finish-status="success">
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>

            <!--表单-->
            <el-form :model="addGoodFrom" :rules="addGoodFromRules" ref="addGoodFromRef" label-position="top">
                <!--标签页-->
                <el-tabs tab-position="left"  v-model="activeIndex" @tab-click="handleTagClick" :before-leave="tabsBeforeLeave">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input  v-model="addGoodFrom.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input  v-model="addGoodFrom.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input  v-model="addGoodFrom.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input  v-model="addGoodFrom.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                            v-model="addGoodFrom.goods_cat"
                            :options="cateList"
                            :props="slectedCateProps"
                            @change="handleChange"
                            clearable
                            >
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :label="item.attr_name" v-for="(item,index) in manyTableData" :key="index">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border  :label="cb" v-for="(cb,cbindex) in item.attr_vals" :key="cbindex"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="(item,index) in onlyTableData" :key="index">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <!-- 
                            action  代表要上传的url地址
                            on-preview  查看图片
                            on-remove 移除图片
                            list-type  指定预览组件呈现方式 我们这里用列表排序
                        -->
                        <el-upload
                            :headers="uploadHeaders"
                            :action="uploadUrl"  
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :on-success="handleUploadSuccess"
                            list-type="picture">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!--富文本编辑器-->
                        <quill-editor v-model="addGoodFrom.goods_introduce"></quill-editor>
                        <el-button type="primary" @click="addGood" class="marginTop20">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>

        <el-dialog
            title="图片预览"
            :visible.sync="picDialogVisible"
            width="50%">
            <img :src="showPicTempUrl" alt="" class="preivewImage">
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash'
import {handleGetCates} from '@/request/cate'
import {handleGetAttrsByCateId} from '@/request/params'
import {handleAddGood} from '@/request/goodList'
export default {
    props: {

    },
    components: {

    },
    data() {
        const checkNumber = (rules,value,callback)=>{
            if(!value){
                return callback(new Error('请输入内容'));
            }else if(value<=0){
                return callback(new Error('数值必须大于0'));
            }else{
                return callback()
            }
        }
        return {
            uploadUrl:'http://127.0.0.1:8888/api/private/v1/upload',  //上传图片url地址
            uploadHeaders:{
                Authorization: window.sessionStorage.getItem('token')
            },
            activeIndex: '0',  //步骤条到达的某个步骤  0开始
            addGoodFrom:{      //添加商品表单绑定数据
                goods_name:'',
                goods_price:0,
                goods_weight:0,
                goods_number:0,
                goods_cat:[],
                pics:[],  //存储将要上传的图片集信息
                goods_introduce:''  //商品详情
            },
            addGoodFromRules:{  //添加商品表单校验规则
                goods_name:[
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 1, max: 5, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                goods_price:[
                    { required: true, message: '请输入商品价格', trigger: 'blur' },
                    { validator: checkNumber, trigger: 'blur'}
                ],
                goods_weight:[
                    { required: true, message: '请输入商品重量', trigger: 'blur' },
                    { validator: checkNumber, trigger: 'blur'}
                ],
                goods_number:[
                    { required: true, message: '请输入商品数量', trigger: 'blur' },
                    { validator: checkNumber, trigger: 'blur'}
                ],
                goods_cat:[
                    { required: true, message: '请选择商品分类', trigger: 'blur' }
                ]
            },
            cateList:[],  //分类级联选择器数据
            slectedCateProps:{    //级联选择器配置对象
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
                //checkStrictly: true   //允许任意选中一二级
            },
            manyTableData:[],   //存储根据分类id请求过来动态参数数据
            onlyTableData:[],    //存储根据分类id请求过来静态属性数据
            showPicTempUrl: '',   //预览图片零时url
            picDialogVisible:false
        };
    },
    computed: {
        cateId(){
            if(this.addGoodFrom.goods_cat.length===3){
                return this.addGoodFrom.goods_cat[2]
            }else{
                return ''
            }
        }
    },
    created() {
        this.handleGetCates()
    },
    mounted() {

    },
    watch: {

    },
    methods: {
        //添加商品方法
        addGood(){
            this.$refs.addGoodFromRef.validate(async valid=>{
                if(valid){  //校验通过
                   //1. 深拷贝一个表单数据
                   const data = _.cloneDeep(this.addGoodFrom)

                   //2. 处理分类
                   data.goods_cat = data.goods_cat.join(',')

                   //3.处理静态属性和动态参数
                   let attrs = []
                   this.manyTableData.forEach(item=>{
                        attrs.push({
                           'attr_id':item.attr_id,
                           'attr_value':item.attr_vals.join(',')
                        })
                   })
                   this.onlyTableData.forEach(item=>{
                        attrs.push({
                           'attr_id':item.attr_id,
                           'attr_value':item.attr_vals
                        })
                   })
                   data.attrs = attrs
                   
                   //4.发起请求
                   handleAddGood(data)
                   .then(res=>{
                        if(res.meta.status!==201){
                            return this.$message.error(res.meta.msg)
                        }else{
                            this.$message.success(res.meta.msg)
                            this.$router.push('/goods')
                        }
                   })
                }else{
                  this.$message.error('请完善商品信息')
                }
            })
        },
        //监听图片上传成功
        handleUploadSuccess(response){
            let picInfo = {pic: response.data.tmp_path}
            this.addGoodFrom.pics.push(picInfo)
        },
        //移除图片
        handleRemove(file){
            //1.获取要移除的图片临时路径
            let filePath = file.response.data.tmp_path

            //2.从pics数组中找到这个图片
            // 使用find函数找到对应索引
            let index = this.addGoodFrom.pics.findIndex(item=>{
                item.pic === filePath
            })

            //3.从pics中移除
            this.addGoodFrom.pics.splice(index,1)
        },
        //查看图片
        handlePreview(file){
            this.showPicTempUrl = file.response.data.url
            this.picDialogVisible = true
        },
        /*
            tabs切换前钩子函数
        */
        tabsBeforeLeave(activeNamen,oldActiveName){
            if(oldActiveName==='0' && this.addGoodFrom.goods_cat.length===0){
                this.$message.error('请先选择商品分类')
                return false
            }else{
                return true
            }
        },
        /*
            点击tabs标签
        */
        handleTagClick(tab){
            //切换到商品参数
            if(tab.name==='1'){
                this.getTableData({sel:'many'})
            }else if(tab.name==='2'){ //切换到属性
                this.getTableData({sel:'only'})
            }
        },
        getTableData(params){
            handleGetAttrsByCateId(this.cateId,params)
                .then(res=>{
                    if(res.meta.status!==200){
                        return this.$message.error('获取分类参数失败')
                    }else{
                        if(params.sel==='many'){
                            res.data.forEach(item=>{
                                if(item.attr_vals===''){
                                    item.attr_vals = []
                                }else{
                                    item.attr_vals = item.attr_vals.split(',')
                                }
                            })
                            this.manyTableData = res.data
                        }else{
                            this.onlyTableData = res.data
                        }
                    }
                })
        },
        /*
            分类级联选择器发生改变
        */
        handleChange(){
            //必须是三级分类  不然直接清空
            if(this.addGoodFrom.goods_cat.length!=3){
                this.addGoodFrom.goods_cat = []
            }
        },
        /*
            获取分类级联选择器数据
        */
        handleGetCates(){
            handleGetCates()
            .then(res=>{
                if(res.meta.status!==200){
                    return this.$message.error('获取分类失败')
                }else{
                    this.cateList = res.data
                }
            })
        }
    },
};
</script>

<style scoped lang="less">
.preivewImage{
    width: 100%;
}
</style>
